<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-input v-model="keyword" placeholder="文章类型名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="warning" v-on:click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		
		<!--列表v-loading="listLoading"-->
		<el-table :data="tableDatas" v-loading="listLoading" @selection-change="handleSelectionChange" highlight-current-row
			style="width: 100%;">
			<!--多选框-->
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="70" label="序号">
			</el-table-column>
			<el-table-column prop="articleName" label="文章名称" width="160" show-overflow-tooltip>
			</el-table-column>
			<el-table-column prop="articlePic" label="封面" width="160" show-overflow-tooltip>
				<template scope="scope">
					<img :src="scope.row.articlePic" height="50px"/>
				</template>
			</el-table-column>
			<el-table-column prop="articleTag" label="文章标签" width="145" show-overflow-tooltip>
			</el-table-column>
			<el-table-column prop="typeName" label="文章类型" width="150" show-overflow-tooltip>
			</el-table-column>
			<el-table-column prop="articleState" label="文章状态" width="100">
				<template scope="scope">
                    <span v-if="scope.row.articleState==1" style="color: blue;">发布</span>
                    <span v-else-if="scope.row.articleState==2" style="color: red;">弃用</span>
					<span v-else style="color: green;">草稿</span>
				</template>
			</el-table-column>
			<el-table-column prop="topState" label="是否置顶" width="100">
				<template scope="scope">
                    <span v-if="!scope.row.topState" style="color: red;">不置顶</span>
					<span v-if="scope.row.topState" style="color: green;">置顶</span>
				</template>
			</el-table-column>
			<el-table-column prop="publishName" label="发布人" width="70">
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" width="150">
			</el-table-column>
			<el-table-column prop="updateTime" label="修改时间" width="150">
			</el-table-column>
			<el-table-column prop="articleReadCount" label="阅读量" width="120" >
			</el-table-column>
			<el-table-column prop="articleStarNum" label="点赞数" width="120" >
			</el-table-column>
			<el-table-column prop="articleCommentNum" label="评论数" width="120" >
			</el-table-column>
			<el-table-column label="操作" width="200">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" :disabled="this.sels.length === 0" @click="handlePatchDel">批量删除</el-button>
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
				:page-sizes="[5, 10, 15]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
				:total="totals" style="float:right;" background>
			</el-pagination>
		</el-col>

		<!--添加或修改界面-->
		<el-dialog title="保存信息" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="文章名称" prop="articleName">
					<el-input v-model="saveForm.articleName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="封面图片">
					<el-upload
						class="upload-demo"
						action="http://localhost:8080/minio"
						:limit=1
						:on-success="handleSuccess"
						:on-remove="handleRemove"
						:file-list="fileList"
						:on-exceed="handleExceed"
						:auto-upload="true"
						list-type="picture">
						<el-button size="small" type="primary">点击上传</el-button>
						<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
					</el-upload>
				</el-form-item>
				<el-form-item label="文章标签">
					<el-input v-model="saveForm.articleTag" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="文章类型">
					<el-cascader
						v-model="saveForm.articleType"
						:options="typeTree"
						:props="{value:'id',label:'typeName', checkStrictly: true ,emitPath:false}"
						clearable>
					</el-cascader>
				</el-form-item>
				<el-form-item label="文章状态">
					<template>
						<el-radio v-model="saveForm.articleState" label="0">草稿</el-radio>
						<el-radio v-model="saveForm.articleState" label="1">发布</el-radio>
						<el-radio v-model="saveForm.articleState" label="2">弃用</el-radio>
					</template>
				</el-form-item>
				<el-form-item label="是否置顶">
					<template>
						<el-radio v-model="saveForm.topState" label="1">置顶</el-radio>
						<el-radio v-model="saveForm.topState" label="0">不置顶</el-radio>
					</template>
				</el-form-item>
				<el-form-item label="备注">
					<el-input type="textarea" v-model="saveForm.articleRemark" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="文章内容">
					<div class="edit_container">
						<quill-editor v-model="saveForm.articleContent"
									:options="editorOption">
						</quill-editor>
					</div>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ["blockquote", "code-block"], // 引用  代码块-----['blockquote', 'code-block']
  [{header: 1}, {header: 2}], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
  [{list: "ordered"}, {list: "bullet"}], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{script: "sub"}, {script: "super"}], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
  [{indent: "-1"}, {indent: "+1"}], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
  [{direction: "rtl"}], // 文本方向-----[{'direction': 'rtl'}]
  [{size: ["small", false, "large", "huge"]}], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
  [{header: [1, 2, 3, 4, 5, 6, false]}], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
  [{color: []}, {background: []}], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
  [{font: []}], // 字体种类-----[{ font: [] }]
  [{align: []}], // 对齐方式-----[{ align: [] }]
  ["clean"], // 清除文本格式-----['clean']
  ["image", "link"] // 链接、图片、视频-----['link', 'image', 'video']
];
export default {
	components: {
        quillEditor
    },
	data() {
		return {
			// 富文本编辑器
			editorOption: {
						modules: {
							//工具栏定义的
							toolbar: toolbarOptions
						},
						//主题
						theme: "snow",
						placeholder: "请开始书写您的博客内容..."
					},
			// 类型树 
			typeTree:[],
			//1.分页查询相关数据
			totals: 0,//总记录条数
			currentPage: 1,//当前页,要传递到后台的
			pageSize: 5, //每页显示多少条
			tableDatas: [], //当前页数据
			listLoading: false,

			//2.高级查询相关数据
			keyword: '',
			time:'',
			startTime:'',
			endTime:'',

			//3.删除相关数据

			//4.批量删除相关数据
			sels: [], //存储多选记录

			//5.添加和修改相关数据
			fileList:[],
			saveFormVisible: false,
			saveForm: {
				id: null,
				articlePic:'',
				articleName:'',
				articleTag:'',
				articleType:'',
				articleState:null,
				topState:null,
				articleRemark:'',
				articleContent:''
			},

			//6.添加和修改校验规则-表单项校验
			saveFormRules: {
				articleName: [
					{ required: true, message: '请输入文章名称', trigger: 'blur' }
				]
			},

		}
	},
	methods: {
		//1.分页查询相关方法
		//1.1.获取列表数据
		getTableData() {
			var params = {
				pageSize: this.pageSize,
				currentPage: this.currentPage,
				keyword: this.keyword,
			};

			this.$http.post("/article",params).then(res=>{
				if(res.data.success){
					this.tableDatas = res.data.data.list;
					this.totals = res.data.data.total;
				}
			})
		},
		//1.2.选择第几页时触发
		handleCurrentChange(curentPage) {
			this.currentPage = curentPage;
			this.getTableData();
		},
		//1.3.选择每页显示记录条数时触发
		handleSizeChange(pageSize) {
			this.pageSize = pageSize;
			this.getTableData();
		},

		//2.高级查询相关方法
		keywordQuery() {
			this.currentPage = 1;
			this.getTableData();
		},

		//3.删除相关方法
		handleDel(row) {
			this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
				type: 'warning'
				}).then(() => {
					this.$http.delete("/article/"+row.id).then(res=>{
						if(res.data.success){
							this.$message({
								type:'success',
								message: '删除成功'
							})
							// 获取文件名
							let pic = row.articlePic;
							let file = pic.substring(pic.lastIndexOf("/")+1);
							// 删除minio上的文件
							this.$http.delete("/minio/"+file).then(res=>{
								console.log(res);
							})
							this.getTableData();
						}else{
							// 发生后端代码错误提示
							this.$message.error("网络波动，请重试。");
						}
					}).catch(res=>{
						// 前端400/404错误提示
						this.$message.error("网络波动，请重试。");
					})	
				}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				});          
			});
		},


		//4.批量删除相关方法
		//4.1.选项改变时触发
		handleSelectionChange(val) {
			this.sels=val;
		},
		//4.2.批量删除
		handlePatchDel() {
			// 获取id的数组
			var ids = this.sels.map(obj=>obj.id);
			this.$confirm('此操作将永久删除这些文件, 是否继续?', '提示', {
				type: 'warning'
				}).then(() => {
					this.$http.patch("/article/",ids).then(res=>{
						if(res.data.success){
							this.$message({
								type:'success',
								message: '删除成功'
							})
							this.getTableData();
						}else{
							// 发生后端代码错误提示
							this.$message.error("网络波动，请重试。");
						}
					}).catch(res=>{
						// 前端400/404错误提示
						this.$message.error("网络波动，请重试。");
					})	
				}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				});          
			});
		},

		//5.添加和修改相关方法
		// 获取类型数
		getTypeTree(){
			this.$http.get("/articleType/typeTree").then((res)=>{
				this.typeTree = res.data.data;
			})
		},
		//5.1.点击添加弹出对话框
		handleAdd() {
			this.fileList = [];
			this.saveForm={
				id: null,
				articlePic:'',
				articleName:'',
				articleTag:'',
				articleType:'',
				articleState:"1",
				topState:"1",
				articleRemark:'',
				articleContent:''	
			};
			this.saveFormVisible=true;
			this.getTypeTree();
		},
		//5.2.点击修改弹出对话框
		handleEdit(row) {
			// 避免页面数据改动，使用assign转换一下
			this.saveForm=Object.assign({},row);
			// 回显单选框
			this.saveForm.articleState=JSON.stringify(row.articleState);
			this.saveForm.topState=JSON.stringify(row.topState);
			this.getTypeTree();
			// 获取图片路径
			var url = row.articlePic;
			// 如果没有图片那么就清空列表
			if (row.articlePic==""){
				this.fileList = [];
			}else{
				// 获取文件名
				var name = url.substring(url.lastIndexOf('/')+1);
				// 手动赋值给图片列表
				this.fileList = [{
					name:name,url:row.articlePic
				}]
			}
			this.saveFormVisible=true;
		},
		//5.3.提交表单数据操作数据库
		saveSubmit() {
			// 表单验证
			this.$refs.saveForm.validate((valid) => {
				if (valid) {
					this.$http.put("/article",this.saveForm).then(res=>{
					if (res.data.success){
						this.$message({
							type:'success',
							message: '操作成功'
						})
						// 刷新
						this.getTableData();
					}else{
						// 发生后端代码错误提示
						this.$message.error("网络波动，请重试。");
					}
					this.saveFormVisible=false;})
			}else {
            this.$message.error("校验未通过");
				}
			});
			this.fileList = [];
		},

		// 上传图片的方法
		// 自动上传图片成功的钩子
		handleSuccess(response, file, fileList){
			// 给articlePic赋值
			this.saveForm.articlePic = "http://127.0.0.1:9005/java-01/"+response.message;
		},
		// 移除图片的钩子
		handleRemove(file,fileList){
			// 获取图片路径
			var fileUrl = file.url;
			// 获取文件名
			var fileName = fileUrl.substring(fileUrl.lastIndexOf('/')+1);
			// 调用删除minio图片接口
			this.$http.delete("/minio/"+fileName).then(res=>{
				if (res.data.success){
					this.$message.success("删除封面成功");
				}else{
					this.$message.error("删除封面失败");
				}
			})
			// 将articlePic赋值为空
			this.saveForm.articlePic = '';
			// 清空图片列表
			this.fileList = [];
		},
		// 图片个数限制钩子
		handleExceed(){
			this.$message.error("只能上传一张封面");
		}

	},
	mounted() {
		this.getTableData();
	}
}

</script>

<style scoped></style>
